<template>
    <main class="container mx-auto p-4">
        <div class="flex flex-col items-center justify-center min-h-screen">
            <!-- 日历头部 -->
            <div
                class="w-full max-w-4xl bg-white rounded-xl shadow-md p-6 mb-6"
            >
                <div class="flex justify-between items-center">
                    <div class="flex items-center space-x-4">
                        <button
                            class="p-2 rounded-full bg-gray-100 hover:bg-gray-200 transition-colors"
                            @click="previousMonth"
                            title="上个月"
                        >
                            <svg
                                xmlns="http://www.w3.org/2000/svg"
                                class="h-5 w-5"
                                fill="none"
                                viewBox="0 0 24 24"
                                stroke="currentColor"
                            >
                                <path
                                    stroke-linecap="round"
                                    stroke-linejoin="round"
                                    stroke-width="2"
                                    d="M15 19l-7-7 7-7"
                                />
                            </svg>
                        </button>
                        <span class="text-xl font-semibold text-gray-700">{{
                            monthName
                        }}</span>
                        <button
                            class="p-2 rounded-full bg-gray-100 hover:bg-gray-200 transition-colors"
                            @click="nextMonth"
                            title="下个月"
                        >
                            <svg
                                xmlns="http://www.w3.org/2000/svg"
                                class="h-5 w-5"
                                fill="none"
                                viewBox="0 0 24 24"
                                stroke="currentColor"
                            >
                                <path
                                    stroke-linecap="round"
                                    stroke-linejoin="round"
                                    stroke-width="2"
                                    d="M9 5l7 7-7 7"
                                />
                            </svg>
                        </button>
                    </div>
                    <button
                        @click="goToToday"
                        class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
                    >
                        今天
                    </button>
                </div>
            </div>

            <!-- 星期标题 -->
            <div class="grid grid-cols-7 w-full max-w-4xl gap-1 mb-2">
                <div
                    v-for="day in [
                        '周一',
                        '周二',
                        '周三',
                        '周四',
                        '周五',
                        '周六',
                        '周日',
                    ]"
                    :key="day"
                    class="text-center font-bold text-gray-600 p-2"
                >
                    {{ day }}
                </div>
            </div>

            <!-- 日历网格 -->
            <div class="grid grid-cols-7 gap-1 w-full max-w-4xl">
                <div
                    v-for="(day, index) in dayArray"
                    :key="index"
                    class="aspect-square"
                    @click="day && clickHandler(day)"
                    @dblclick="day && doubleClickHandler(day)"
                >
                    <div
                        v-if="day"
                        class="calendar-cell rounded-lg bg-white shadow-sm flex flex-col overflow-hidden border border-gray-200 h-full w-full hover:shadow-md transition-all cursor-pointer"
                        :class="{
                            'bg-green-50 border-green-300': day.isToday,
                            'bg-blue-50 border-blue-300': isSelectedDay(day),
                        }"
                    >
                        <div class="p-2 flex-grow flex flex-col">
                            <div class="flex justify-between items-start">
                                <span
                                    class="font-bold text-lg"
                                    :class="{
                                        'text-green-600': day.isToday,
                                        'text-blue-600':
                                            isSelectedDay(day) && !day.isToday,
                                    }"
                                >
                                    {{ day.num }}
                                </span>
                                <span
                                    v-if="day.isToday"
                                    class="text-xs bg-green-500 text-white px-2 py-1 rounded-full"
                                >
                                    今天
                                </span>
                            </div>
                            <div class="mt-1 flex-grow overflow-hidden">
                                <!-- 这里可以显示当天的活动 -->
                                <div
                                    class="events-container space-y-1 max-h-20 overflow-y-auto"
                                >
                                    <div
                                        v-for="event in getEventsForDay(
                                            day.date,
                                        )"
                                        :key="event.id"
                                        class="event-item text-xs p-1 rounded border-l-2 truncate cursor-pointer hover:opacity-80 transition-opacity"
                                        :class="
                                            getEventTypeClass(event.type_id)
                                        "
                                        :title="
                                            event.title +
                                            ' - ' +
                                            extractTimeFromDateTime(
                                                event.start_time,
                                            ) +
                                            '~' +
                                            extractTimeFromDateTime(
                                                event.end_time,
                                            )
                                        "
                                        @click.stop="showEventPreview(event)"
                                    >
                                        <div class="flex items-center">
                                            <span
                                                class="w-1 h-1 rounded-full bg-current mr-1 flex-shrink-0"
                                            ></span>
                                            <span class="truncate flex-1">{{
                                                event.title
                                            }}</span>
                                        </div>
                                        <div
                                            class="text-xs opacity-75 truncate"
                                        >
                                            {{
                                                extractTimeFromDateTime(
                                                    event.start_time,
                                                )
                                            }}~{{
                                                extractTimeFromDateTime(
                                                    event.end_time,
                                                )
                                            }}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 今日事件模态框 -->
        <dialog id="eventsToday" class="modal w-full">
            <div class="modal-box">
                <h1 class="font-bold text-2xl mb-4">
                    今日事件 - {{ selectedDateString }}
                </h1>

                <div
                    v-if="eventsThisDay.length === 0"
                    class="text-center py-8 text-gray-500"
                >
                    暂无事件
                </div>

                <ul v-else class="space-y-2 max-h-96 overflow-y-auto">
                    <li
                        v-for="(event, index) in eventsThisDay"
                        :key="index"
                        class="p-3 bg-gray-50 rounded-lg border cursor-pointer hover:bg-gray-100 transition-colors"
                        @dblclick="openEditEventModal(event)"
                    >
                        <div class="flex justify-between items-start">
                            <h3 class="font-semibold">{{ event.title }}</h3>
                            <div class="flex space-x-2">
                                <span
                                    class="text-sm bg-blue-100 text-blue-800 px-2 py-1 rounded"
                                >
                                    {{ getTypeName(event.type_id) }}
                                </span>
                                <span
                                    class="text-sm bg-green-100 text-green-800 px-2 py-1 rounded"
                                >
                                    {{ getStatusName(event.status) }}
                                </span>
                            </div>
                        </div>
                        <p class="text-gray-600 mt-1">{{ event.content }}</p>
                        <div class="text-sm text-gray-500 mt-2">
                            {{ extractTimeFromDateTime(event.start_time) }} -
                            {{ extractTimeFromDateTime(event.end_time) }}
                        </div>
                        <div class="text-xs text-gray-400 mt-1">
                            双击编辑此事件
                        </div>
                    </li>
                </ul>

                <div class="modal-action">
                    <button class="btn btn-primary" @click="openAddEventModal">
                        新增事件
                    </button>
                    <button class="btn" @click="eventsTodayModal.close">
                        关闭
                    </button>
                </div>
            </div>
        </dialog>

        <!-- 新增/编辑事件模态框 -->
        <dialog id="addEventModel" class="modal">
            <div class="modal-box">
                <h1 class="font-bold text-2xl mb-4">
                    {{ modalTitle }} - {{ selectedDateString }}
                </h1>

                <form @submit.prevent="saveEvent" class="space-y-4">
                    <!-- 标题 -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text">标题 *</span>
                        </label>
                        <input
                            type="text"
                            placeholder="输入事件标题"
                            v-model="eventForm.title"
                            required
                            class="input input-bordered w-full"
                            :class="{ 'input-error': formErrors.title }"
                        />
                        <label class="label" v-if="formErrors.title">
                            <span class="label-text-alt text-error">{{
                                formErrors.title
                            }}</span>
                        </label>
                    </div>

                    <!-- 内容 -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text">事件详情</span>
                        </label>
                        <textarea
                            placeholder="输入事件详情"
                            v-model="eventForm.content"
                            class="textarea textarea-bordered w-full h-24"
                        ></textarea>
                    </div>

                    <!-- 类型、状态和时间 -->
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <!-- 事件类型 -->
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text">事件类型</span>
                            </label>
                            <select
                                v-model="eventForm.type_id"
                                class="select select-bordered w-full"
                            >
                                <option
                                    v-for="type in typeOptions"
                                    :key="type.id"
                                    :value="type.id"
                                >
                                    {{ type.name }}
                                </option>
                            </select>
                        </div>

                        <!-- 事件状态 -->
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text">事件状态</span>
                            </label>
                            <select
                                v-model="eventForm.status"
                                class="select select-bordered w-full"
                            >
                                <option
                                    v-for="status in statusOptions"
                                    :key="status.id"
                                    :value="status.id"
                                >
                                    {{ status.name }}
                                </option>
                            </select>
                        </div>

                        <!-- 时间选择 -->
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text">开始时间 *</span>
                            </label>
                            <input
                                type="time"
                                v-model="eventForm.start_time"
                                class="input input-bordered"
                                :class="{
                                    'input-error': formErrors.start_time,
                                }"
                            />
                            <label class="label" v-if="formErrors.start_time">
                                <span class="label-text-alt text-error">{{
                                    formErrors.start_time
                                }}</span>
                            </label>
                        </div>

                        <div class="form-control">
                            <label class="label">
                                <span class="label-text">结束时间 *</span>
                            </label>
                            <input
                                type="time"
                                v-model="eventForm.end_time"
                                class="input input-bordered"
                                :class="{ 'input-error': formErrors.end_time }"
                            />
                            <label class="label" v-if="formErrors.end_time">
                                <span class="label-text-alt text-error">{{
                                    formErrors.end_time
                                }}</span>
                            </label>
                        </div>
                    </div>

                    <div class="modal-action">
                        <button type="submit" class="btn btn-primary">
                            {{ isEditing ? "更新事件" : "保存事件" }}
                        </button>
                        <button
                            type="button"
                            class="btn"
                            @click="addEventModal.close"
                        >
                            取消
                        </button>
                    </div>
                </form>
            </div>
        </dialog>

        <!-- 事件预览模态框 -->
        <dialog id="eventPreview" class="modal">
            <div class="modal-box">
                <h3 class="font-bold text-lg mb-2">
                    {{ previewEvent?.title }}
                </h3>
                <div class="space-y-2">
                    <div class="flex items-center">
                        <span class="text-sm text-gray-600 w-16">类型:</span>
                        <span class="text-sm">{{
                            getTypeName(previewEvent?.type_id || 0)
                        }}</span>
                    </div>
                    <div class="flex items-center">
                        <span class="text-sm text-gray-600 w-16">状态:</span>
                        <span class="text-sm">{{
                            getStatusName(previewEvent?.status || 0)
                        }}</span>
                    </div>
                    <div class="flex items-center">
                        <span class="text-sm text-gray-600 w-16">时间:</span>
                        <span class="text-sm">
                            {{
                                extractTimeFromDateTime(
                                    previewEvent?.start_time || "",
                                )
                            }}
                            -
                            {{
                                extractTimeFromDateTime(
                                    previewEvent?.end_time || "",
                                )
                            }}
                        </span>
                    </div>
                    <div class="flex items-start">
                        <span class="text-sm text-gray-600 w-16">内容:</span>
                        <span class="text-sm flex-1">{{
                            previewEvent?.content || "无"
                        }}</span>
                    </div>
                </div>
                <div class="modal-action">
                    <button
                        class="btn btn-primary"
                        @click="openEditEventModal(previewEvent!)"
                    >
                        编辑
                    </button>
                    <button class="btn" @click="closeEventPreview">关闭</button>
                </div>
            </div>
        </dialog>
    </main>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive } from "vue";
import { invoke } from "@tauri-apps/api/core";
import { DateUtils } from "../utils/date.ts";
import { debug, error as logError } from "@tauri-apps/plugin-log";

// 类型定义
interface CalendarDay {
    num: number;
    isToday: boolean;
    date: Date;
}

interface Event {
    id: number;
    title: string;
    content: string;
    type_id: number;
    status: number;
    end_time: string;
    start_time: string;
}

interface EventForm {
    id: number;
    title: string;
    content: string;
    type_id: number;
    status: number;
    end_time: string;
    start_time: string;
    original_start_date?: string; // 新增：保存原始开始日期
    original_end_date?: string; // 新增：保存原始结束日期
}

// 响应式数据
const currentDate = ref(new Date());
const currentMonth = ref(currentDate.value.getMonth());
const currentYear = ref(currentDate.value.getFullYear());
const selectedDay = ref<{ num: number; date: Date } | null>(null);

const eventsThisMonth = ref<Event[]>([]);
const eventsThisDay = ref<Event[]>([]);
const previewEvent = ref<Event | null>(null);

// 表单数据和状态
const eventForm = reactive<EventForm>({
    id: 0,
    title: "",
    content: "",
    type_id: 0,
    status: 0,
    end_time: "09:00",
    start_time: "08:00",
});

const isEditing = ref(false); // 标记是编辑模式还是新增模式

// 表单验证
const formErrors = reactive({
    title: "",
    start_time: "",
    end_time: "",
});

const typeOptions = [
    { id: 2, name: "订单" },
    { id: 1, name: "材料" },
    { id: 3, name: "个人事情" },
    { id: 0, name: "其他" },
];

const statusOptions = [
    { id: 0, name: "未完成" },
    { id: 1, name: "已完成" },
    { id: 2, name: "已取消" },
    { id: 3, name: "过期" },
];

// 计算属性
const dayArray = computed(() => {
    const array: (CalendarDay | null)[] = [];
    const firstDayOfMonth = new Date(currentYear.value, currentMonth.value, 1);
    const offset = (firstDayOfMonth.getDay() + 6) % 7;
    const daysInMonth = new Date(
        currentYear.value,
        currentMonth.value + 1,
        0,
    ).getDate();
    const today = new Date();

    // 添加偏移量
    for (let i = 0; i < offset; i++) {
        array.push(null);
    }

    // 添加当前月的日期
    for (let i = 1; i <= daysInMonth; i++) {
        const date = new Date(currentYear.value, currentMonth.value, i);
        array.push({
            num: i,
            isToday: date.toDateString() === today.toDateString(),
            date,
        });
    }

    // 确保日历总是6行
    while (array.length < 42) {
        array.push(null);
    }

    return array;
});

const monthName = computed(() => {
    return new Date(currentYear.value, currentMonth.value).toLocaleString(
        "zh-CN",
        {
            month: "long",
            year: "numeric",
        },
    );
});

const selectedDateString = computed(() => {
    if (!selectedDay.value) return "";
    return `${currentYear.value}-${(currentMonth.value + 1).toString().padStart(2, "0")}-${selectedDay.value.num.toString().padStart(2, "0")}`;
});

const modalTitle = computed(() => {
    return isEditing.value ? "编辑事件" : "新增事件";
});

// 方法
function previousMonth() {
    currentMonth.value--;
    if (currentMonth.value < 0) {
        currentMonth.value = 11;
        currentYear.value--;
    }
    selectedDay.value = null;
    loadEventsForMonth();
}

function nextMonth() {
    currentMonth.value++;
    if (currentMonth.value > 11) {
        currentMonth.value = 0;
        currentYear.value++;
    }
    selectedDay.value = null;
    loadEventsForMonth();
}

function goToToday() {
    const today = new Date();
    currentMonth.value = today.getMonth();
    currentYear.value = today.getFullYear();

    // 找到今天对应的日历项
    const todayDay = dayArray.value.find(
        (day) => day && day.date.toDateString() === today.toDateString(),
    );

    if (todayDay) {
        selectedDay.value = {
            num: todayDay.num,
            date: todayDay.date,
        };
    }

    loadEventsForMonth();
}

// 单击处理
function clickHandler(day: CalendarDay) {
    if (!day) return;

    selectedDay.value = {
        num: day.num,
        date: day.date,
    };
}

function doubleClickHandler(day: CalendarDay) {
    if (!day) return;

    selectedDay.value = {
        num: day.num,
        date: day.date,
    };
    loadEventsForDay(day.date);
    eventsTodayModal.showModal();
}

// 检查是否是选中的日期
function isSelectedDay(day: CalendarDay): boolean {
    if (!selectedDay.value) return false;

    return selectedDay.value.date.toDateString() === day.date.toDateString();
}

// 获取某一天的事件 - 修复版本
function getEventsForDay(date: Date): Event[] {
    if (!eventsThisMonth.value.length) return [];

    const targetDateStr = formatDateToYMD(date);

    return eventsThisMonth.value.filter((event) => {
        try {
            const eventDateStr = formatDateToYMD(new Date(event.start_time));
            return eventDateStr === targetDateStr;
        } catch (error) {
            console.error("Error parsing event date:", error, event);
            return false;
        }
    });
}

// 格式化日期为 YYYY-MM-DD
function formatDateToYMD(date: Date): string {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, "0");
    const day = date.getDate().toString().padStart(2, "0");
    return `${year}-${month}-${day}`;
}

// 获取事件类型对应的样式类
function getEventTypeClass(typeId: number): string {
    switch (typeId) {
        case 1: // 材料
            return "bg-blue-50 border-blue-300 text-blue-700 hover:bg-blue-100";
        case 2: // 订单
            return "bg-green-50 border-green-300 text-green-700 hover:bg-green-100";
        case 3: // 个人事情
            return "bg-purple-50 border-purple-300 text-purple-700 hover:bg-purple-100";
        default: // 其他
            return "bg-gray-50 border-gray-300 text-gray-700 hover:bg-gray-100";
    }
}

// 显示事件预览
function showEventPreview(event: Event) {
    previewEvent.value = event;

    // 确保事件数据完整
    if (!previewEvent.value) return;

    console.log("Preview event:", previewEvent.value);
    eventPreviewModal.showModal();
}

// 关闭事件预览
function closeEventPreview() {
    previewEvent.value = null;
    eventPreviewModal.close();
}

function loadEventsForDay(date: Date) {
    const startDate = new Date(
        date.getFullYear(),
        date.getMonth(),
        date.getDate(),
    );
    const endDate = new Date(
        date.getFullYear(),
        date.getMonth(),
        date.getDate() + 1,
    );

    const start_time = DateUtils.format(startDate);
    const end_time = DateUtils.format(endDate);

    invoke("list_event", { start_time, end_time })
        .then((resp: any) => {
            if (resp.status_code === 200) {
                eventsThisDay.value = resp.data;
            } else {
                logError(`Failed to load events: ${resp.message}`);
            }
        })
        .catch((error) => {
            logError(`Error loading events: ${error}`);
        });
}

// 加载月份事件 - 添加错误处理
function loadEventsForMonth() {
    const firstDay = new Date(currentYear.value, currentMonth.value, 1);
    const firstDayNextMonth = new Date(
        currentYear.value,
        currentMonth.value + 1,
        1,
    );

    const start_time = DateUtils.format(firstDay);
    const end_time = DateUtils.format(firstDayNextMonth);

    console.log("Loading events for month:", {
        year: currentYear.value,
        month: currentMonth.value + 1,
        start_time,
        end_time,
    });

    invoke("list_event", { start_time, end_time })
        .then((data: any) => {
            console.log("Month events response:", data);
            if (data.status_code === 200) {
                eventsThisMonth.value = data.data || [];
                debug(
                    `Loaded ${eventsThisMonth.value.length} events for month`,
                );

                // 调试：打印每个日期的事件数量
                if (eventsThisMonth.value.length > 0) {
                    const eventsByDate: { [key: string]: number } = {};
                    eventsThisMonth.value.forEach((event) => {
                        const dateStr = formatDateToYMD(
                            new Date(event.start_time),
                        );
                        eventsByDate[dateStr] =
                            (eventsByDate[dateStr] || 0) + 1;
                    });
                    console.log("Events by date:", eventsByDate);
                }
            } else {
                logError(`Failed to load events: ${data.message}`);
                eventsThisMonth.value = [];
            }
        })
        .catch((error) => {
            logError(`Error loading month events: ${error}`);
            eventsThisMonth.value = [];
        });
}

function getTypeName(typeId: number): string {
    const type = typeOptions.find((t) => t.id === typeId);
    return type ? type.name : "未知";
}

function getStatusName(statusId: number): string {
    const status = statusOptions.find((s) => s.id === statusId);
    return status ? status.name : "未知";
}

function validateForm(): boolean {
    let isValid = true;

    // 重置错误
    Object.keys(formErrors).forEach((key) => {
        (formErrors as any)[key] = "";
    });

    // 验证标题
    if (!eventForm.title.trim()) {
        formErrors.title = "标题不能为空";
        isValid = false;
    }

    // 验证时间
    if (!eventForm.start_time) {
        formErrors.start_time = "请选择开始时间";
        isValid = false;
    }

    if (!eventForm.end_time) {
        formErrors.end_time = "请选择结束时间";
        isValid = false;
    }

    // 验证时间逻辑
    if (eventForm.start_time && eventForm.end_time) {
        const start = new Date(`2000-01-01T${eventForm.start_time}`);
        const end = new Date(`2000-01-01T${eventForm.end_time}`);
        if (end <= start) {
            formErrors.end_time = "结束时间必须晚于开始时间";
            isValid = false;
        }
    }

    return isValid;
}

function resetForm() {
    Object.assign(eventForm, {
        id: 0,
        title: "",
        content: "",
        type_id: 0,
        status: 0,
        end_time: "09:00",
        start_time: "08:00",
        original_start_date: undefined,
        original_end_date: undefined,
    });

    Object.keys(formErrors).forEach((key) => {
        (formErrors as any)[key] = "";
    });

    isEditing.value = false;
}

function openAddEventModal() {
    if (!selectedDay.value) {
        alert("请先选择日期");
        return;
    }
    resetForm();
    // 设置默认时间为当前选择日期的合理时间
    eventForm.start_time = "08:00";
    eventForm.end_time = "09:00";
    addEventModal.showModal();
}

function openEditEventModal(event: Event) {
    // 填充表单数据
    Object.assign(eventForm, {
        id: event.id,
        title: event.title,
        content: event.content,
        type_id: event.type_id,
        status: event.status,
        // 提取时间部分（假设存储的是完整日期时间字符串）
        start_time: extractTimeFromDateTime(event.start_time),
        end_time: extractTimeFromDateTime(event.end_time),
        // 保存原始日期部分
        original_start_date: extractDateFromDateTime(event.start_time),
        original_end_date: extractDateFromDateTime(event.end_time),
    });

    isEditing.value = true;
    addEventModal.showModal();
}

// 从日期时间字符串中提取时间部分 - 增强版本
function extractTimeFromDateTime(dateTimeStr: string): string {
    if (!dateTimeStr) return "08:00";

    try {
        // 处理不同的日期时间格式
        let date: Date;

        if (dateTimeStr.includes("T")) {
            // ISO 格式：2024-01-01T08:00:00
            date = new Date(dateTimeStr);
        } else if (dateTimeStr.includes(" ")) {
            // 空格分隔格式：2024-01-01 08:00:00
            date = new Date(dateTimeStr.replace(" ", "T"));
        } else {
            // 只有时间：08:00
            return dateTimeStr;
        }

        if (isNaN(date.getTime())) {
            console.warn("Invalid date:", dateTimeStr);
            return "08:00";
        }

        return `${date.getHours().toString().padStart(2, "0")}:${date.getMinutes().toString().padStart(2, "0")}`;
    } catch (e) {
        console.error("Error parsing date:", e, dateTimeStr);
        return "08:00";
    }
}

// 从日期时间字符串中提取日期部分
function extractDateFromDateTime(dateTimeStr: string): string {
    if (!dateTimeStr) return "";

    try {
        // 处理不同的日期时间格式
        let date: Date;

        if (dateTimeStr.includes("T")) {
            // ISO 格式：2024-01-01T08:00:00
            date = new Date(dateTimeStr);
        } else if (dateTimeStr.includes(" ")) {
            // 空格分隔格式：2024-01-01 08:00:00
            date = new Date(dateTimeStr.replace(" ", "T"));
        } else {
            // 只有时间，没有日期
            return "";
        }

        if (isNaN(date.getTime())) {
            console.warn("Invalid date:", dateTimeStr);
            return "";
        }

        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`;
    } catch (e) {
        console.error("Error parsing date:", e, dateTimeStr);
        return "";
    }
}

async function saveEvent() {
    if (!validateForm()) {
        return;
    }

    try {
        let startDateTime: string;
        let endDateTime: string;

        if (isEditing.value) {
            // 编辑模式：使用原始事件的日期部分
            if (
                !eventForm.original_start_date ||
                !eventForm.original_end_date
            ) {
                alert("无法获取原始事件日期，请重新编辑");
                return;
            }

            startDateTime = `${eventForm.original_start_date} ${eventForm.start_time}`;
            endDateTime = `${eventForm.original_end_date} ${eventForm.end_time}`;

            debug(`Updating event: ${eventForm.title} (ID: ${eventForm.id})`);

            const result = await invoke("update_event", {
                id: eventForm.id,
                title: eventForm.title,
                content: eventForm.content,
                type_id: eventForm.type_id,
                status: eventForm.status,
                end_time: endDateTime,
                start_time: startDateTime,
            });

            console.log("Event updated:", result);
        } else {
            // 新增模式：使用选中的日期
            if (!selectedDay.value) {
                alert("请先选择日期");
                return;
            }

            startDateTime = `${selectedDateString.value} ${eventForm.start_time}`;
            endDateTime = `${selectedDateString.value} ${eventForm.end_time}`;

            debug(`Creating event: ${eventForm.title}`);

            const result = await invoke("create_event", {
                title: eventForm.title,
                content: eventForm.content,
                type_id: eventForm.type_id,
                end_time: endDateTime,
                start_time: startDateTime,
            });

            console.log("Event created:", result);
        }

        // 重新加载事件
        if (selectedDay.value) {
            loadEventsForDay(selectedDay.value.date);
        }
        loadEventsForMonth();

        // 关闭模态框
        addEventModal.close();
    } catch (error) {
        logError(
            `Failed to ${isEditing.value ? "update" : "create"} event: ${error}`,
        );
        alert(`${isEditing.value ? "更新" : "创建"}事件失败，请重试`);
    }
}

// 模态框引用
const eventsTodayModal = {
    showModal: () => {
        const dialog = document.getElementById(
            "eventsToday",
        ) as HTMLDialogElement;
        dialog?.showModal();
    },
    close: () => {
        const dialog = document.getElementById(
            "eventsToday",
        ) as HTMLDialogElement;
        dialog?.close();
    },
};

const addEventModal = {
    showModal: () => {
        const dialog = document.getElementById(
            "addEventModel",
        ) as HTMLDialogElement;
        dialog?.showModal();
    },
    close: () => {
        const dialog = document.getElementById(
            "addEventModel",
        ) as HTMLDialogElement;
        dialog?.close();
    },
};

const eventPreviewModal = {
    showModal: () => {
        const dialog = document.getElementById(
            "eventPreview",
        ) as HTMLDialogElement;
        dialog?.showModal();
    },
    close: () => {
        const dialog = document.getElementById(
            "eventPreview",
        ) as HTMLDialogElement;
        dialog?.close();
    },
};

// 生命周期
onMounted(() => {
    const today = new Date();
    const todayDay = dayArray.value.find(
        (day) => day && day.date.toDateString() === today.toDateString(),
    );

    if (todayDay) {
        selectedDay.value = {
            num: todayDay.num,
            date: todayDay.date,
        };
    }

    loadEventsForMonth();
});
</script>

<style scoped>
.calendar-cell {
    transition: all 0.2s ease;
    min-height: 120px;
}

.calendar-cell:hover {
    transform: scale(1.02);
    z-index: 10;
    background-color: #f8fafc;
}

/* 今天和选中状态的样式增强 */
.calendar-cell.bg-green-50 {
    background-color: #dcfce7 !important;
    border-color: #22c55e !important;
}

.calendar-cell.bg-blue-50 {
    background-color: #dbeafe !important;
    border-color: #3b82f6 !important;
}

/* 模态框背景 */
.modal-box {
    max-width: 500px;
    width: 90vw;
}

/* 事件容器样式 */
.events-container {
    scrollbar-width: thin;
    scrollbar-color: #cbd5e1 #f1f5f9;
}

.events-container::-webkit-scrollbar {
    width: 3px;
}

.events-container::-webkit-scrollbar-track {
    background: #f1f5f9;
    border-radius: 2px;
}

.events-container::-webkit-scrollbar-thumb {
    background: #cbd5e1;
    border-radius: 2px;
}

.events-container::-webkit-scrollbar-thumb:hover {
    background: #94a3b8;
}

.event-item {
    transition: all 0.2s ease;
    border-left-width: 3px;
    padding: 2px 4px;
}

.event-item:hover {
    transform: translateX(2px);
}
</style>
